package com.seeyon.apps.demo.manager;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;

import com.seeyon.apps.demo.Constants4Demo;
import com.seeyon.apps.demo.dao.DemoDao;
import com.seeyon.apps.demo.po.Demo;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.organization.dao.OrgHelper;
import com.seeyon.ctp.util.Datetimes;
import com.seeyon.ctp.util.FlipInfo;
import com.seeyon.ctp.util.ParamUtil;
import com.seeyon.ctp.util.annotation.Inject;


public class DemoManagerImpl implements DemoManager {
	@Inject
	private DemoDao demoDao;
		
	@Override
	public void saveDemo(Map<String, Object> params) throws BusinessException {
		Demo demo = new Demo();
		ParamUtil.mapToBean(params, demo, true);
		demo.setIdIfNew();
		demo.setCreateMember(AppContext.currentUserId());
		demo.setCreateTime(new Date());
		demo.setDeleteFlag(Constants4Demo.deleteFlag.ENABLE.ordinal());
		demoDao.save(demo);
	}

	@Override
	public FlipInfo findDemoList(FlipInfo flipInfo, Map<String, Object> params) throws BusinessException {
		demoDao.findDemoList(flipInfo, Constants4Demo.deleteFlag.ENABLE.ordinal());
		
		List<Map<String, Object>> dbList = flipInfo.getData();
		if(CollectionUtils.isNotEmpty(dbList)) {
			List<Demo> demoList = ParamUtil.mapsToBeans(dbList, Demo.class, true);
			
			List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
			for (Demo demo : demoList) {
				Map<String, Object> map = new HashMap<>();
				map.put("id", demo.getId());
				map.put("title", demo.getTitle());
				map.put("remark", demo.getRemark());
				map.put("remarkDate", Datetimes.format(demo.getRemarkDate(), Datetimes.dateStyle));
				map.put("createMember", OrgHelper.showMemberName(demo.getCreateMember()));
				map.put("createTime", Datetimes.format(demo.getCreateTime(), Datetimes.datetimeStyle));
				result.add(map);
			}
			
			flipInfo.setData(result);
		}
		
		return flipInfo;
	}

	@Override
	public void deleteDemo(List<String> ids) throws BusinessException {
		List<Long> cdids = ids.stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
		demoDao.deleteById(cdids);
	}
	
}
